package com.witmore.neutron.ai.cognitive.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.jetbrains.annotations.NotNull;
import org.springframework.ai.content.Media;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.ObjectUtils;

import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;

public class MediaJsonConverter {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String mediaToJson(Media media) {
        try {
            // 构造可序列化的 DTO 对象
            MediaDTO dto = getMediaDTO(media);
            return objectMapper.writeValueAsString(dto);
        } catch (Exception e) {
            throw new RuntimeException("Media 转换 JSON 失败", e);
        }
    }

    @NotNull
    private static MediaDTO getMediaDTO(Media media) {
        MediaDTO dto = new MediaDTO();
        dto.setData(media.getData() instanceof byte[] ?
                Base64.getEncoder().encodeToString((byte[]) media.getData()) :
                media.getData().toString());
        dto.setName(media.getName());
        dto.setMimeType(ObjectUtils.isEmpty(media.getMimeType()) ? null : JSONArray.toJSONString(media.getMimeType()));
        dto.setId(media.getId());
        return dto;
    }

    public static String mediaListToJson(List<Media> mediaList) {
        try {
            // 将 Media 列表转换为 DTO 列表
            List<MediaDTO> dtoList = mediaList.stream().map(MediaJsonConverter::getMediaDTO).toList();
            return objectMapper.writeValueAsString(dtoList);
        } catch (Exception e) {
            throw new RuntimeException("Media 列表转换 JSON 失败", e);
        }
    }

    /**
     * [
     * {"id":null,
     * "mimeType":"{\"concrete\":true,\"parameters\":{},\"subtype\":\"png\",\"type\":\"image\",\"wildcardSubtype\":false,\"wildcardType\":false}",
     * <p>
     * "data":"https://witmore.oss-cn-hangzhou.aliyuncs.com/agent/azF8HktJBnAlUkuo/2025-06-09/1749462574363_576.jpeg",
     * <p>
     * "name":"media-png-cd8ea8fe-79d0-4066-82bf-ca8a7eb947b0"
     * }
     * <p>
     * ]
     */
    public static String mediaListToImagesList(List<Media> mediaList) {
        if (ObjectUtils.isEmpty(mediaList)) {
            return null;
        }
        // 将 Media 列表转换为 DTO 列表
        List<MediaDTO> dtoList = mediaList.stream().map(MediaJsonConverter::getMediaDTO).toList();
        return dtoList.stream().map(media -> {
            String mimeType = media.getMimeType();
            JSONObject jsonObject = JSONObject.parseObject(mimeType);
            String type = jsonObject.getString("type");
            if (type.equalsIgnoreCase("image")) {
                return media.getData().toString();
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.joining(","));
    }

    // 内部 DTO 类
    @Data
    private static class MediaDTO {
        private String id;

        private String mimeType;

        private Object data;

        private String name;
    }

    public static void main(String[] args) {
        String content = "r3e62tyhuiopjjhbjk";
        String imageUrl = "https://witmore.oss-cn-hangzhou.aliyuncs.com/agent/azF8HktJBnAlUkuo/2025-06-09/1749462574363_576.jpeg";
        List<Media> mediaList = Collections.singletonList(new Media(MimeTypeUtils.IMAGE_PNG, URI.create(imageUrl)));
        String s = mediaListToImagesList(mediaList);
        System.out.printf(s);
    }

}